<script setup lang="ts">
import {ref, computed,inject,nextTick} from 'vue'
import {Message} from "@arco-design/web-vue";
import {saveAs} from 'file-saver';
import {dict} from '@/api/system/dict.js';
import feeType from '@/api/finance/feeType.js';
import jsonBig from "json-bigint";
import Print from "@/utils/print";
import DataGrid from "@cps/DataGrid/DataGrid.vue";

const props = defineProps({
  visible: Boolean,
  crudRef: {
    required: true
  },
  selected: {
    type: Array,
    default: () => []
  },
})
const config = ref({
  title: '',
  data: [],
  api: Function,
  displayDataIndex: '',
  form: {},
  ApiType: undefined,
  isDownload: undefined,
  isPrint: undefined,
})
const form = ref({})
const loading = ref({
  value: false,
  count: 0,
})
const visible = ref()
const records = ref([])
const emit = defineEmits(['cancel'])
const options = computed(() => {
  let defaultOptions = {
    showButtons: false
  }
  return {...defaultOptions, ...config.value.form.options}
})
/*
* @param button
* @param button.title 窗口标题
* @param button.api   接口地址
* @param button.form  表单配置
* @param button.action  自定义方法,优先级高于api
* @param button.displayDataIndex  展示编号的字段,默认 shipment_no > number > name
* */
const open = async (button) => {
  if (!props.selected || props.selected.length == 0) {
    Message.error('至少选择一条数据')
    return;
  }
  if (button.action && typeof button.action === 'function') {
    button.action(props.selected)
    return;
  }
  if (!button.api || ('function' !== typeof button.api && 'function' !== typeof button.api.value)) {
    Message.error('缺少接口配置')
    return;
  }
  let api = typeof button.api === 'object' ? button.api.value : button.api
  config.value.title = 'object' === typeof button.title ? button.title.value : button.title
  config.value.displayDataIndex = button.displayDataIndex ? button.displayDataIndex : ''
  config.value.api = api
  config.value.form = button.form ? button.form : null
  config.value.ApiType = button.ApiType ? button.ApiType : null
  config.value.isDownload = button.isDownload ? button.isDownload : null
  config.value.isPrint = button.isPrint ? button.isPrint : null
  let keyIndex =  config.value.form?.id || 'id'
  records.value = JSON.parse(JSON.stringify(props.crudRef.getTableData().filter(i => props.selected.includes(i[keyIndex]))))
  form.value = button.form?.form ? JSON.parse(JSON.stringify(button.form.form)) : {}
  loading.value = {
    value: false,
    count: 0,
  }

  if (config.value.isPrint) {
    const key = config.value.form?.key || 'ids';
    let response = await config.value.api(Object.assign({[key]: props.selected}, form.value))
    if(!response.success){
      // console.log(response)
      Message.error(response.message)
      return;
    }
    content.value = response.data
  }
  visible.value = true
  buttonDisabled.value = false
  let res = await dict.getDict('currencyType')
  res.data.map(i=>{
    currency.value.push(i.title)
    currency_desc.value[i.title] = i.key
  })
  currency.value = []
  // currency_desc.value = []
  res = await feeType.list({})
  res.data.map(i=>{
    fee_type.value.push(i.fee_name)
    fee_type_desc.value[i.fee_name] = i.id
  })
  fee_type.value = []
  // fee_type_desc.value = []
  userData.value = [
    {
      business_at: getCurrentDate(),
      fee_type_desc: '',
      currency_desc: '人民币',
      unit_desc: 'KG',
      unit_amount: '',
      memo: '',
      remark: '',
    }
  ]
  nextTick(() => {
    if(recordsList.value?.clientHeight){
      let height = recordsList.value.clientHeight; // 获取元素高度
      recordsListHeight.value=height/records.value.length
    }
  })
}
const getCurrentDate = ()=> {
    const now = new Date();

    const year = now.getFullYear();

    // 注意：JavaScript的月份是从0开始的，所以需要加1
    const month = String(now.getMonth() + 1).padStart(2, '0');

    // 注意：JavaScript的日期也是从1开始的，所以不需要额外处理
    const date = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
}
const handleScroll=()=>{
}
const cancel = () => {
  form.value = {}
  config.value.form = {}
  visible.value = false
}
defineExpose({
  open,
})
const recordsList = ref(null);
const recordsMain = ref(null);
const recordsListHeight=ref(null)
const percent = computed(() => {
  if(records.value.length>10 && loading.value.count>10){
     recordsMain.value.scrollTop =recordsListHeight.value*(loading.value.count-7)
  }
  let topercent=loading.value.count / records.value.length
  return topercent.toFixed(2);
})
const content = ref([])
const buttonDisabled = ref(false)
const submitApi = async ()=>{
  if(loading.value.value){
    Message.warning('数据正在执行中请稍后再试!')
    return false
  }
  if (loading.value.count > 0) {
    cancel()
    return;
  }
  let feeList = userData.value.filter(j=>{
      return j.business_at || j.fee_type_desc || j.currency_desc || j.unit_desc || j.unit_amount || j.unit || j.memo || j.remark
    })
  for(let i = 0 ; i < feeList.length; i++){
    //  if(!feeList[i].business_at){
    //       Message.error('业务时间必填')
    //       return;
    //  }
     if(!feeList[i].fee_type_desc){
          Message.error('费用类型必填')
          return;
     }
     if(!feeList[i].currency_desc){
          Message.error('币种必填')
          return;
     }
     if(!feeList[i].unit_desc){
          Message.error('单位必填')
          return;
     }
     if(!feeList[i].unit_amount){
          Message.error('单位费用必填')
          return;
     }
     feeList[i].invoices_type = form.value.invoices_type
  }
  buttonDisabled.value = true
  feeList.map(j=>{
      j = descToId(fee_type_desc.value,'fee_type',j)
      j = descToId(currency_desc.value,'currency',j)
      j = descToId(unit_desc.value,'unit',j)
  })
  loading.value.value = true
  for(let i = 0 ; i < records.value.length; i++){
    let item = records.value[i]
    item.loading = true
     try {
      let res = await config.value.api(item.id,{fees:feeList})
      item.success = res.success === true
      item.result = res.message || (res.success === true ? `成功！` : `失败！`)
      } catch (e) {  
        item.success = false
        item.result = e.message || `失败！`
      } finally {
        loading.value.count++
        item.loading = false
      }
  }
  loading.value.value = false
  props.crudRef.refresh()
}
const descToId = (list,key,data)=>{
  for(let k in list){
    if(k == data[key+'_desc']){
          data[key] = list[k]
      }
  }
  return data
}

const fee_type = ref([])
const fee_type_desc = ref({})
const currency = ref([])
const currency_desc = ref({})
const unit = ref(['KG','m³','票'])
const unit_desc = ref({
  'KG':'1',
  'm³':'2',
  '票':'3'
})

const userData = ref([
  {
    business_at: '2024-07-20',
    fee_type_desc: '',
    currency_desc: '人民币',
    unit_desc: 'KG',
    unit_amount: '1',
    memo: '',
    remark: '',}
])

const columns = ref([
  {title: '业务时间', data: 'business_at',type: 'date', dateFormat: 'YYYY-MM-DD HH:mm:ss'},
  {title: '费用类型', data: 'fee_type_desc',required:true,
    type: 'dropdown',
    source: fee_type.value
  },
  {title: '币种', data: 'currency_desc',required:true,
    type: 'dropdown',
    source: currency.value
  },
  {title: '汇率', data: 'unit'},
  {title: '单位', data: 'unit_desc',required:true,
    type: 'dropdown',
    source: unit.value
  },
  {title: '单位费用', data: 'unit_amount',required:true,type:'numeric'},
  {title: '描述', data: 'memo'},
  {title: '备注', data: 'remark'},
])
</script>

<template>
  <a-modal :title="config.title" :visible='visible' @cancel="cancel" width="60%"
           unmount-on-close
           :hide-cancel="loading.count > 0"
           :closable="!loading.value"
           :escToClose="!loading.value">
    <p style="color:red">注：不填写业务时间则使用拣货时间来生成流水</p>
    <br />
    <!-- todo 成功批量反馈增加结果下载    -->
    <div v-if="!config.isDownload && !config.isPrint">
      <a-progress :percent="percent" v-if="loading.count"></a-progress>
      <data-grid :columns="columns" v-model="userData"/>
      <div ref="recordsMain" class="h-96 overflow-y-auto"  @scroll="handleScroll">
        <div ref="recordsList">
          <a-row justify="start" v-for="(item,i) in records"
                class="border align-center justify-center text-center items-center"
                :class="{
          'bg-gray-300':item.loading,
          'bg-green-300':item.success,
          'bg-red-300':!item.success && item.result
              }">
            <a-col :span="2" class="bg-gray-300 h-8 leading-8">{{ i + 1 }}</a-col>
            <a-col :span="14" class="h-8 leading-8">
              {{ item[config.displayDataIndex] || item.shipment_no || item.number || item.name || item.id }}
            </a-col>
            <a-col :span="8" class="h-8 leading-8 overflow-hidden">
              <a-spin v-if="item.loading"></a-spin>
              <div v-else class="overflow-hidden">{{ item.result }}</div>
            </a-col>
          </a-row>
        </div>
      </div>
    </div>
    <template #footer>
      <a-button v-if="loading.count == 0" @click="visible=false">取消</a-button>
      <a-button type="primary" @click="submitApi()">{{ loading.count > 0 ? '关闭' : '提交' }}</a-button>  
    </template>
  </a-modal>
</template>

<style scoped>
@media print {
  .print-break{
    break-after: page;
  }
}
</style>